package com.daydayup.learn.redisCache;


import com.daydayup.learn.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    public static final String CACHE_KEY_USER = "user:";

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public int addUser(User user) {
        if (user.getDeleted() == null) {
            user.setDeleted(0);
        }
        if (user.getUpdateTime() == null) {
            user.setUpdateTime(new Date());
        }
        if (user.getCreateTime() == null) {
            user.setCreateTime(new Date());
        }
        log.info("插入之前user:{}",user);
        int retVal = userMapper.addUser(user);
        log.info("插入之后user:{}",user);
        log.info("=================================");
        if(retVal > 0) {
            //到数据库里面，重新捞出新数据出来，做缓存
            user = this.userMapper.getUserById(user.getId());
            //缓存key
            String key = CACHE_KEY_USER+user.getId();
            //往mysql里面插入成功随后再从mysql查询出来，再插入redis
            redisTemplate.opsForValue().set(key,user);
        }
        return retVal;
    }

    @Override
    @MyRedisCache(keyPrefix = "user",matchValue = "#id")
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }
}
